<?php
/**
 * 首页统计服务
 * 实现复杂的统计数据查询和数据权限控制
 */

declare(strict_types=1);

namespace app\service;

use think\facade\Db;
use think\facade\Cache;

class DashboardStatsService
{
    protected $permissionService;

    public function __construct()
    {
        $this->permissionService = new DataPermissionService();
    }

    /**
     * 获取首页统计数据（精简版）
     * @param int $userId 用户ID
     * @return array
     */
    public function getDashboardStats(int $userId): array
    {
        if ($userId <= 0) {
            throw new \Exception('用户ID不能为空');
        }

        try {
            // 获取用户信息
            $userInfo = $this->getUserInfo($userId);

            // 只返回前端实际需要的数据
            $result = [
                'user_info' => $userInfo,
                'quick_actions' => $this->getQuickActions($userId),
                'permissions' => [
                    'is_leader' => false,
                    'department_count' => 0,
                    'can_approve' => false,
                    'permission_level' => 'staff'
                ],
                'stats' => [
                    // 保留空的stats结构以保持兼容性，但移除所有子统计项
                    'overview' => [],
                    'finance' => [],
                    'business' => [],
                    'pending' => [],
                    'schedule' => [
                        'today' => [],
                        'upcoming' => [],
                        'statistics' => [
                            'today_count' => 0,
                            'upcoming_count' => 0,
                            'week_total' => 0,
                            'urgent_count' => 0,
                            'month_total' => 0
                        ]
                    ],
                    'messages' => [
                        'latest' => [],
                        'stats' => [
                            'total' => 0,
                            'unread' => 0,
                            'read' => 0
                        ]
                    ],
                    'comprehensive' => []
                ],
                'summary' => [
                    'total_items' => 0,
                    'pending_count' => 0,
                    'unread_count' => 0
                ],
                'last_update' => time()
            ];

            return $result;
            
        } catch (\Exception $e) {
            // 返回最简默认数据
            return [
                'user_info' => [
                    'id' => $userId,
                    'name' => '未知用户',
                    'dept_name' => '未知部门',
                    'position_name' => '未知职位'
                ],
                'quick_actions' => $this->getQuickActions($userId),
                'permissions' => [
                    'is_leader' => false,
                    'department_count' => 0,
                    'can_approve' => false,
                    'permission_level' => 'staff'
                ],
                'stats' => [
                    'overview' => [],
                    'finance' => [],
                    'business' => [],
                    'pending' => [],
                    'schedule' => [],
                    'messages' => [],
                    'comprehensive' => []
                ],
                'summary' => [
                    'total_items' => 0,
                    'pending_count' => 0,
                    'unread_count' => 0
                ],
                'last_update' => time()
            ];
        }
    }

    /**
     * 获取概览统计（模拟原项目 main() 方法的复杂逻辑）
     * @param int $userId 用户ID
     * @return array
     */
    private function getOverviewStats(int $userId): array
    {
        $stats = [];
        
        // 获取用户的领导部门（模拟原项目 get_leader_departments 函数）
        $userInfo = $this->getUserInfo($userId);
        $leaderDepartments = $this->getLeaderDepartments($userId);
        
        // 1. 财务统计 - 模拟原项目的财务统计逻辑
        $financeStats = $this->getFinanceOverviewStats($userId, $leaderDepartments);
        $stats = array_merge($stats, $financeStats);
        
        // 2. 客户统计 - 复杂的权限查询
        $customerStats = $this->getCustomerOverviewStats($userId, $leaderDepartments);
        $stats = array_merge($stats, $customerStats);
        
        // 3. 合同统计 - 销售合同和采购合同
        $contractStats = $this->getContractOverviewStats($userId, $leaderDepartments);
        $stats = array_merge($stats, $contractStats);
        
        // 4. 项目任务统计
        $projectStats = $this->getProjectOverviewStats($userId);
        $stats = array_merge($stats, $projectStats);
        
        // 5. 案件统计
        $lawcaseStats = $this->getLawcaseOverviewStats($userId, $leaderDepartments);
        $stats = array_merge($stats, $lawcaseStats);
        
        return $stats;
    }
    
    /**
     * 获取案件概览统计
     * @param int $userId 用户ID
     * @param array $leaderDepartments 领导部门列表
     * @return array
     */
    private function getLawcaseOverviewStats(int $userId, array $leaderDepartments): array
    {
        $stats = [];
        
        // 构建案件数据权限条件
        $whereLawcase = [['delete_time', '=', 0]];
        $whereLawcaseOr = [
            ['admin_id', '=', $userId],
            ['lawyer_id', '=', $userId]
        ];
        
        // 添加共享权限
        $whereLawcaseOr[] = ['', 'exp', Db::raw("FIND_IN_SET('{$userId}', share_ids)")];
        
        if (!empty($leaderDepartments)) {
            $whereLawcaseOr[] = ['did', 'in', $leaderDepartments];
        }
        
        try {
            $lawcaseCount = Db::name('lawcase')
                ->where($whereLawcase)
                ->where(function ($query) use ($whereLawcaseOr) {
                    foreach ($whereLawcaseOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '案件总量',
                'value' => $lawcaseCount,
                'icon' => 'scale',
                'color' => '#ff4d4f',
                'trend' => $this->getTrend('lawcase', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '案件总量',
                'value' => 0,
                'icon' => 'scale',
                'color' => '#ff4d4f'
            ];
        }
        
        return $stats;
    }

    /**
     * 获取财务概览统计（模拟原项目逻辑）
     * @param int $userId 用户ID
     * @param array $leaderDepartments 领导部门列表
     * @return array
     */
    private function getFinanceOverviewStats(int $userId, array $leaderDepartments): array
    {
        $stats = [];
        
        // 构建财务数据权限条件（模拟原项目 whereFinance 逻辑）
        $whereFinance = [
            ['delete_time', '=', 0],
            ['check_status', '=', 2] // 已审批通过
        ];
        
        $whereFinanceOr = [
            ['admin_id', '=', $userId]
        ];
        
        if (!empty($leaderDepartments)) {
            $whereFinanceOr[] = ['did', 'in', $leaderDepartments];
        }
        
        // 报销总数
        try {
            $expenseCount = Db::name('expense')
                ->where($whereFinance)
                ->where(function ($query) use ($whereFinanceOr) {
                    foreach ($whereFinanceOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '报销总数',
                'value' => $expenseCount,
                'icon' => 'pay-circle',
                'color' => '#1890ff',
                'trend' => $this->getTrend('expense', $userId)
            ];
        } catch (\Exception $e) {
            // 表不存在时返回0
            $stats[] = [
                'name' => '报销总数',
                'value' => 0,
                'icon' => 'pay-circle',
                'color' => '#1890ff'
            ];
        }
        
        // 开票总数
        try {
            $invoiceCount = Db::name('invoice')
                ->where($whereFinance)
                ->where(function ($query) use ($whereFinanceOr) {
                    foreach ($whereFinanceOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '开票总数',
                'value' => $invoiceCount,
                'icon' => 'file-done',
                'color' => '#52c41a',
                'trend' => $this->getTrend('invoice', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '开票总数',
                'value' => 0,
                'icon' => 'file-done',
                'color' => '#52c41a'
            ];
        }
        
        // 收票总数
        try {
            $ticketCount = Db::name('ticket')
                ->where($whereFinance)
                ->where(function ($query) use ($whereFinanceOr) {
                    foreach ($whereFinanceOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '收票总数',
                'value' => $ticketCount,
                'icon' => 'file-add',
                'color' => '#fa8c16',
                'trend' => $this->getTrend('ticket', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '收票总数',
                'value' => 0,
                'icon' => 'file-add',
                'color' => '#fa8c16'
            ];
        }
        
        return $stats;
    }

    /**
     * 获取客户概览统计（模拟原项目复杂权限查询）
     * @param int $userId 用户ID
     * @param array $leaderDepartments 领导部门列表
     * @return array
     */
    private function getCustomerOverviewStats(int $userId, array $leaderDepartments): array
    {
        $stats = [];
        
        // 构建客户数据权限条件（模拟原项目 whereCustomerOr 逻辑）
        $whereCustomer = [['delete_time', '=', 0]];
        $whereCustomerOr = [
            ['belong_uid', '=', $userId]
        ];
        
        if (!empty($leaderDepartments)) {
            $whereCustomerOr[] = ['belong_did', 'in', $leaderDepartments];
        }
        
        // 添加共享权限（模拟原项目 FIND_IN_SET 逻辑）
        $whereCustomerOr[] = ['', 'exp', Db::raw("FIND_IN_SET('{$userId}', share_ids)")];
        
        try {
            $customerCount = Db::name('customer')
                ->where($whereCustomer)
                ->where(function ($query) use ($whereCustomerOr) {
                    foreach ($whereCustomerOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '客户总数',
                'value' => $customerCount,
                'icon' => 'user',
                'color' => '#722ed1',
                'trend' => $this->getTrend('customer', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '客户总数',
                'value' => 0,
                'icon' => 'user',
                'color' => '#722ed1'
            ];
        }
        
        return $stats;
    }

    /**
     * 获取合同概览统计（模拟原项目逻辑）
     * @param int $userId 用户ID
     * @param array $leaderDepartments 领导部门列表
     * @return array
     */
    private function getContractOverviewStats(int $userId, array $leaderDepartments): array
    {
        $stats = [];
        
        // 构建合同数据权限条件（模拟原项目 whereContractOr 逻辑）
        $whereContract = [['delete_time', '=', 0]];
        $whereContractOr = [
            ['admin_id', '=', $userId],
            ['prepared_uid', '=', $userId],
            ['sign_uid', '=', $userId],
            ['keeper_uid', '=', $userId]
        ];
        
        // 添加共享和审批权限
        $whereContractOr[] = ['', 'exp', Db::raw("FIND_IN_SET('{$userId}', share_ids)")];
        $whereContractOr[] = ['', 'exp', Db::raw("FIND_IN_SET('{$userId}', check_uids)")];
        $whereContractOr[] = ['', 'exp', Db::raw("FIND_IN_SET('{$userId}', check_history_uids)")];
        
        if (!empty($leaderDepartments)) {
            $whereContractOr[] = ['did', 'in', $leaderDepartments];
        }
        
        // 销售合同统计
        try {
            $contractCount = Db::name('contract')
                ->where($whereContract)
                ->where(function ($query) use ($whereContractOr) {
                    foreach ($whereContractOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '销售合同',
                'value' => $contractCount,
                'icon' => 'file-text',
                'color' => '#13c2c2',
                'trend' => $this->getTrend('contract', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '销售合同',
                'value' => 0,
                'icon' => 'file-text',
                'color' => '#13c2c2'
            ];
        }
        
        // 采购合同统计
        try {
            $purchaseCount = Db::name('purchase')
                ->where($whereContract)
                ->where(function ($query) use ($whereContractOr) {
                    foreach ($whereContractOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
            
            $stats[] = [
                'name' => '采购合同',
                'value' => $purchaseCount,
                'icon' => 'shopping-cart',
                'color' => '#eb2f96',
                'trend' => $this->getTrend('purchase', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '采购合同',
                'value' => 0,
                'icon' => 'shopping-cart',
                'color' => '#eb2f96'
            ];
        }
        
        return $stats;
    }

    /**
     * 获取项目概览统计（模拟原项目逻辑）
     * @param int $userId 用户ID
     * @return array
     */
    private function getProjectOverviewStats(int $userId): array
    {
        $stats = [];
        
        // 获取用户参与的项目（模拟原项目 project_ids 逻辑）
        try {
            $projectIds = Db::name('project_user')
                ->where(['uid' => $userId, 'delete_time' => 0])
                ->column('project_id');
            
            $whereProject = [
                ['delete_time', '=', 0],
                ['id', 'in', $projectIds]
            ];
            
            $projectCount = Db::name('project')->where($whereProject)->count();
            
            $stats[] = [
                'name' => '项目总数',
                'value' => $projectCount,
                'icon' => 'project',
                'color' => '#f5222d',
                'trend' => $this->getTrend('project', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '项目总数',
                'value' => 0,
                'icon' => 'project',
                'color' => '#f5222d'
            ];
        }
        
        // 任务统计（模拟原项目复杂的 whereOr 逻辑）
        try {
            $whereOr = [
                [['admin_id', '=', $userId]],
                [['director_uid', '=', $userId]],
                [['', 'exp', Db::raw("FIND_IN_SET({$userId}, assist_admin_ids)")]]
            ];
            
            if (!empty($projectIds)) {
                $whereOr[] = [['project_id', 'in', $projectIds]];
            }
            
            $taskCount = Db::name('project_task')
                ->where(function ($query) use ($whereOr) {
                    foreach ($whereOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->where([['delete_time', '=', 0]])
                ->count();
            
            $stats[] = [
                'name' => '任务总数',
                'value' => $taskCount,
                'icon' => 'check-circle',
                'color' => '#389e0d',
                'trend' => $this->getTrend('task', $userId)
            ];
        } catch (\Exception $e) {
            $stats[] = [
                'name' => '任务总数',
                'value' => 0,
                'icon' => 'check-circle',
                'color' => '#389e0d'
            ];
        }
        
        return $stats;
    }

    /**
     * 获取领导部门列表（模拟原项目 get_leader_departments 函数）
     * @param int $userId 用户ID
     * @return array
     */
    private function getLeaderDepartments(int $userId): array
    {
        $departments = [];
        
        // 获取用户所在部门
        $user = Db::name('admin')
            ->where('id', $userId)
            ->find();
        
        if ($user) {
            // 获取用户作为领导的部门（正确的方式：查询department表的leader_id字段）
            $leaderDepts = Db::name('department')
                ->where('leader_id', $userId)
                ->column('id');
            
            if (!empty($leaderDepts)) {
                $departments = array_merge($departments, $leaderDepts);
                
                // 获取所有领导部门的下级部门
                foreach ($leaderDepts as $deptId) {
                    $subDepts = Db::name('department')
                        ->where('parent_id', $deptId)
                        ->where('status', 1)
                        ->column('id');
                    $departments = array_merge($departments, $subDepts);
                }
            }
            
            // 根据职位等级获取管理范围
            $position = Db::name('position')
                ->where('id', $user['position_id'])
                ->find();
            
            if ($position && isset($position['level']) && $position['level'] >= 3) {
                $allDepts = Db::name('department')
                    ->where('status', 1)
                    ->column('id');
                $departments = array_merge($departments, $allDepts);
            }
        }
        
        return array_unique(array_filter($departments));
    }

    /**
     * 获取财务统计
     * @param int $userId 用户ID
     * @return array
     */
    private function getFinanceStats(int $userId): array
    {
        $stats = [];

        // 财务数据权限条件
        $financeWhere = [
            ['delete_time', '=', 0],
            ['check_status', '=', 2] // 已审批通过
        ];

        // 报销统计
        $expenseQuery = Db::name('expense')->where($financeWhere);
        $expenseQuery = $this->permissionService->applyPermissionToQuery($expenseQuery, $userId, 'expense');
        
        $expenseCount = $expenseQuery->count();
        $expenseAmount = $expenseQuery->sum('amount') ?: 0;

        $stats[] = [
            'name' => '报销申请',
            'count' => $expenseCount,
            'amount' => $expenseAmount,
            'amount_format' => number_format($expenseAmount, 2),
            'icon' => 'pay-circle',
            'color' => '#722ed1'
        ];

        // 开票统计
        $invoiceQuery = Db::name('invoice')->where($financeWhere);
        $invoiceQuery = $this->permissionService->applyPermissionToQuery($invoiceQuery, $userId, 'invoice');
        
        $invoiceCount = $invoiceQuery->count();
        $invoiceAmount = $invoiceQuery->sum('amount') ?: 0;

        $stats[] = [
            'name' => '开票申请',
            'count' => $invoiceCount,
            'amount' => $invoiceAmount,
            'amount_format' => number_format($invoiceAmount, 2),
            'icon' => 'file-done',
            'color' => '#13c2c2'
        ];

        // 收票统计
        $ticketQuery = Db::name('ticket')->where($financeWhere);
        $ticketQuery = $this->permissionService->applyPermissionToQuery($ticketQuery, $userId, 'ticket');
        
        $ticketCount = $ticketQuery->count();
        $ticketAmount = $ticketQuery->sum('amount') ?: 0;

        $stats[] = [
            'name' => '收票登记',
            'count' => $ticketCount,
            'amount' => $ticketAmount,
            'amount_format' => number_format($ticketAmount, 2),
            'icon' => 'file-add',
            'color' => '#eb2f96'
        ];

        return $stats;
    }

    /**
     * 获取业务统计
     * @param int $userId 用户ID
     * @return array
     */
    private function getBusinessStats(int $userId): array
    {
        $stats = [];

        // 本月新增客户
        $monthStart = strtotime(date('Y-m-01'));
        $customerQuery = Db::name('customer')
            ->where([
                ['delete_time', '=', 0],
                ['create_time', '>=', $monthStart]
            ]);
        $customerQuery = $this->permissionService->applyPermissionToQuery($customerQuery, $userId, 'customer');
        $newCustomers = $customerQuery->count();

        $stats['new_customers'] = [
            'name' => '本月新增客户',
            'value' => $newCustomers,
            'type' => 'month_new'
        ];

        // 本月新签合同
        $contractQuery = Db::name('contract')
            ->where([
                ['delete_time', '=', 0],
                ['create_time', '>=', $monthStart]
            ]);
        $contractQuery = $this->permissionService->applyPermissionToQuery($contractQuery, $userId, 'contract');
        $newContracts = $contractQuery->count();

        $stats['new_contracts'] = [
            'name' => '本月新签合同',
            'value' => $newContracts,
            'type' => 'month_new'
        ];

        // 合同金额统计
        $contractAmountQuery = Db::name('contract')
            ->where([
                ['delete_time', '=', 0],
                ['check_status', '=', 2]
            ]);
        $contractAmountQuery = $this->permissionService->applyPermissionToQuery($contractAmountQuery, $userId, 'contract');
        $totalAmount = $contractAmountQuery->sum('amount') ?: 0;

        $stats['contract_amount'] = [
            'name' => '合同总金额',
            'value' => $totalAmount,
            'value_format' => number_format($totalAmount, 2),
            'type' => 'amount'
        ];

        // 1. 合同类统计
        $stats['contract_stats'] = $this->getContractTypeStats($userId);
        
        // 2. 合同金额统计
        $contractAmountStatsService = new ContractAmountStatsService();
        $stats['finance_by_period'] = $contractAmountStatsService->getFinanceByPeriod($userId);
        
        // 3. 客户类统计
        $stats['customer_stats'] = $this->getCustomerTypeStats($userId);
        
        // 4. 案件各阶段统计
        $stats['lawcase_stage_stats'] = $this->getLawcaseStageStats($userId);

        return $stats;
    }
    
    /**
     * 获取合同类型统计（案件委托合同和法务合同）
     * @param int $userId 用户ID
     * @return array
     */
    private function getContractTypeStats(int $userId): array
    {
        $contractStats = [];
        
        // 构建合同数据权限条件
        $whereContract = [['delete_time', '=', 0], ['check_status', '=', 2]];
        
        try {
            // 案件委托合同统计
            $caseEntrustQuery = Db::name('contract')
                ->where($whereContract)
                ->where('type', 'like', '%案件委托%');
            $caseEntrustQuery = $this->permissionService->applyPermissionToQuery($caseEntrustQuery, $userId, 'contract');
            
            $caseEntrustCount = $caseEntrustQuery->count();
            $caseEntrustAmount = $caseEntrustQuery->sum('amount') ?: 0;
            $caseEntrustAvg = $caseEntrustCount > 0 ? round($caseEntrustAmount / $caseEntrustCount, 2) : 0;
            
            $contractStats['case_entrust'] = [
                'name' => '案件委托合同',
                'count' => $caseEntrustCount,
                'amount' => $caseEntrustAmount,
                'average' => $caseEntrustAvg,
                'amount_format' => number_format($caseEntrustAmount, 2),
                'average_format' => number_format($caseEntrustAvg, 2)
            ];
            
            // 法务合同统计
            $legalQuery = Db::name('contract')
                ->where($whereContract)
                ->where('type', 'like', '%法务%');
            $legalQuery = $this->permissionService->applyPermissionToQuery($legalQuery, $userId, 'contract');
            
            $legalCount = $legalQuery->count();
            $legalAmount = $legalQuery->sum('amount') ?: 0;
            $legalAvg = $legalCount > 0 ? round($legalAmount / $legalCount, 2) : 0;
            
            $contractStats['legal'] = [
                'name' => '法务合同',
                'count' => $legalCount,
                'amount' => $legalAmount,
                'average' => $legalAvg,
                'amount_format' => number_format($legalAmount, 2),
                'average_format' => number_format($legalAvg, 2)
            ];
        } catch (\Exception $e) {
            $contractStats['case_entrust'] = [
                'name' => '案件委托合同',
                'count' => 0,
                'amount' => 0,
                'average' => 0,
                'amount_format' => '0.00',
                'average_format' => '0.00'
            ];
            $contractStats['legal'] = [
                'name' => '法务合同',
                'count' => 0,
                'amount' => 0,
                'average' => 0,
                'amount_format' => '0.00',
                'average_format' => '0.00'
            ];
        }
        
        return $contractStats;
    }
    
    /**
     * 获取客户类型统计（企业客户和个人客户）
     * @param int $userId 用户ID
     * @return array
     */
    private function getCustomerTypeStats(int $userId): array
    {
        $customerStats = [];
        
        // 构建客户数据权限条件
        $whereCustomer = [['delete_time', '=', 0]];
        
        try {
            // 企业客户统计
            $companyQuery = Db::name('customer')
                ->where($whereCustomer)
                ->where('type', '=', 1); // 1 代表企业客户
            $companyQuery = $this->permissionService->applyPermissionToQuery($companyQuery, $userId, 'customer');
            
            $companyCount = $companyQuery->count();
            $companyMemberCount = $companyQuery->where('is_member', '=', 1)->count();
            $companyNonMemberCount = $companyCount - $companyMemberCount;
            
            $customerStats['company'] = [
                'name' => '企业客户',
                'total' => $companyCount,
                'member' => $companyMemberCount,
                'non_member' => $companyNonMemberCount
            ];
            
            // 个人客户统计
            $individualQuery = Db::name('customer')
                ->where($whereCustomer)
                ->where('type', '=', 2); // 2 代表个人客户
            $individualQuery = $this->permissionService->applyPermissionToQuery($individualQuery, $userId, 'customer');
            
            $individualCount = $individualQuery->count();
            $individualMemberCount = $individualQuery->where('is_member', '=', 1)->count();
            $individualNonMemberCount = $individualCount - $individualMemberCount;
            
            $customerStats['individual'] = [
                'name' => '个人客户',
                'total' => $individualCount,
                'member' => $individualMemberCount,
                'non_member' => $individualNonMemberCount
            ];
        } catch (\Exception $e) {
            $customerStats['company'] = [
                'name' => '企业客户',
                'total' => 0,
                'member' => 0,
                'non_member' => 0
            ];
            $customerStats['individual'] = [
                'name' => '个人客户',
                'total' => 0,
                'member' => 0,
                'non_member' => 0
            ];
        }
        
        return $customerStats;
    }
    
    /**
     * 获取案件各阶段统计
     * @param int $userId 用户ID
     * @return array
     */
    private function getLawcaseStageStats(int $userId): array
    {
        $stageStats = [];
        
        // 构建案件数据权限条件
        $whereLawcase = [['delete_time', '=', 0]];
        
        try {
            $lawcaseQuery = Db::name('lawcase')->where($whereLawcase);
            $lawcaseQuery = $this->permissionService->applyPermissionToQuery($lawcaseQuery, $userId, 'lawcase');
            
            // 获取案件总量
            $totalCount = $lawcaseQuery->count();
            
            // 获取各阶段案件数量
            $stages = $lawcaseQuery
                ->field('stage, count(*) as count')
                ->group('stage')
                ->select()
                ->toArray();
            
            // 定义案件阶段映射（根据实际系统配置调整）
            $stageMapping = [
                1 => '咨询阶段',
                2 => '立案阶段',
                3 => '审理阶段',
                4 => '执行阶段',
                5 => '结案阶段'
            ];
            
            // 转换阶段数据格式
            $stageData = [];
            $totalStageCount = 0;
            foreach ($stages as $stage) {
                $stageName = $stageMapping[$stage['stage']] ?? '未知阶段';
                $stageData[] = [
                    'stage' => $stage['stage'],
                    'stage_name' => $stageName,
                    'count' => $stage['count']
                ];
                $totalStageCount += $stage['count'];
            }
            
            // 如果有未分组的案件（阶段值不在映射中），添加到未知阶段
            if ($totalCount > $totalStageCount) {
                $unknownCount = $totalCount - $totalStageCount;
                $stageData[] = [
                    'stage' => 0,
                    'stage_name' => '未知阶段',
                    'count' => $unknownCount
                ];
            }
            
            $stageStats = [
                'total_count' => $totalCount,
                'stages' => $stageData
            ];
        } catch (\Exception $e) {
            $stageStats = [
                'total_count' => 0,
                'stages' => []
            ];
        }
        
        return $stageStats;
    }

    /**
     * 获取待办事项统计（模拟原项目 todue 逻辑）
     * @param int $userId 用户ID
     * @return array
     */
    private function getPendingStats(int $userId): array
    {
        $stats = [];
        $leaderDepartments = $this->getLeaderDepartments($userId);

        // 1. 待审批的工作流
        try {
            $pendingApprovals = Db::name('workflow_approval_step')
                ->alias('s')
                ->join('workflow_approval a', 's.approval_id = a.id')
                ->where([
                    ['s.approver_id', '=', $userId],
                    ['s.status', '=', 0], // 待处理
                    ['a.status', 'in', [0, 1]] // 待审批或审批中
                ])
                ->group('a.type')
                ->field('a.type, count(*) as count')
                ->select()
                ->toArray();

            foreach ($pendingApprovals as $approval) {
                $typeName = $this->getApprovalTypeName($approval['type']);
                $stats[] = [
                    'type' => $approval['type'],
                    'name' => '待审' . $typeName,
                    'count' => $approval['count'],
                    'priority' => 'high',
                    'url' => '/workflow/pending?type=' . $approval['type']
                ];
            }
        } catch (\Exception $e) {
            // 工作流表不存在时跳过
        }

        // 2. 快到期合同统计（模拟原项目 todue 逻辑）
        try {
            $todueTime = strtotime('+30 days'); // 30天内到期
            $whereContract = [
                ['delete_time', '=', 0],
                ['check_status', '=', 2], // 已审批
                ['end_time', '>', time()],
                ['end_time', '<=', $todueTime]
            ];
            
            $whereContractOr = [
                ['admin_id', '=', $userId],
                ['keeper_uid', '=', $userId]
            ];
            
            if (!empty($leaderDepartments)) {
                $whereContractOr[] = ['did', 'in', $leaderDepartments];
            }
            
            $todueContracts = Db::name('contract')
                ->where($whereContract)
                ->where(function ($query) use ($whereContractOr) {
                    foreach ($whereContractOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
                
            if ($todueContracts > 0) {
                $stats[] = [
                    'type' => 'contract_todue',
                    'name' => '即将到期合同',
                    'count' => $todueContracts,
                    'priority' => 'medium',
                    'url' => '/contract/todue'
                ];
            }
        } catch (\Exception $e) {
            // 合同表不存在时跳过
        }

        // 3. 超期项目任务（模拟原项目逻辑）
        try {
            $overdueTime = time();
            $whereTask = [
                ['delete_time', '=', 0],
                ['status', '<', 3], // 未完成
                ['end_time', '<', $overdueTime]
            ];
            
            $whereTaskOr = [
                ['admin_id', '=', $userId],
                ['director_uid', '=', $userId],
                ['', 'exp', Db::raw("FIND_IN_SET({$userId}, assist_admin_ids)")]
            ];
            
            $overdueTasks = Db::name('project_task')
                ->where($whereTask)
                ->where(function ($query) use ($whereTaskOr) {
                    foreach ($whereTaskOr as $condition) {
                        $query->whereOr($condition);
                    }
                })
                ->count();
                
            if ($overdueTasks > 0) {
                $stats[] = [
                    'type' => 'task_overdue',
                    'name' => '超期任务',
                    'count' => $overdueTasks,
                    'priority' => 'high',
                    'url' => '/project/task/overdue'
                ];
            }
        } catch (\Exception $e) {
            // 任务表不存在时跳过
        }

        // 4. 未读消息统计
        try {
            $unreadMessages = Db::name('message')
                ->where([
                    ['to_uid', '=', $userId],
                    ['read_time', '=', 0],
                    ['delete_time', '=', 0]
                ])
                ->count();

            if ($unreadMessages > 0) {
                $stats[] = [
                    'type' => 'message',
                    'name' => '未读消息',
                    'count' => $unreadMessages,
                    'priority' => 'low',
                    'url' => '/message/index'
                ];
            }
        } catch (\Exception $e) {
            // 消息表不存在时跳过
        }

        // 5. 待处理报销（针对财务人员）
        try {
            $pendingExpense = Db::name('expense')
                ->where([
                    ['delete_time', '=', 0],
                    ['check_status', '=', 1] // 审批中
                ])
                ->where(function ($query) use ($userId, $leaderDepartments) {
                    $query->whereOr([
                        ['', 'exp', Db::raw("FIND_IN_SET({$userId}, check_uids)")]
                    ]);
                    if (!empty($leaderDepartments)) {
                        $query->whereOr(['did', 'in', $leaderDepartments]);
                    }
                })
                ->count();
                
            if ($pendingExpense > 0) {
                $stats[] = [
                    'type' => 'expense_pending',
                    'name' => '待处理报销',
                    'count' => $pendingExpense,
                    'priority' => 'medium',
                    'url' => '/expense/pending'
                ];
            }
        } catch (\Exception $e) {
            // 报销表不存在时跳过
        }

        return $stats;
    }

    /**
     * 获取日程安排统计（增强版）
     * @param int $userId 用户ID
     * @return array
     */
    private function getScheduleStats(int $userId): array
    {
        $today = strtotime(date('Y-m-d'));
        $tomorrow = $today + 86400;
        $weekEnd = $today + 7 * 86400;
        $monthEnd = strtotime('+1 month', $today);

        $result = [
            'today' => [],
            'upcoming' => [],
            'weekly' => [],
            'statistics' => []
        ];

        try {
            // 1. 今日日程（详细信息）
            $todaySchedule = Db::name('schedule')
                ->where([
                    ['admin_id', '=', $userId],
                    ['delete_time', '=', 0],
                    ['start_time', '>=', $today],
                    ['start_time', '<', $tomorrow]
                ])
                ->order('start_time asc')
                ->limit(10)
                ->select()
                ->each(function($item) {
                    $item['start_time_format'] = date('H:i', $item['start_time']);
                    $item['end_time_format'] = date('H:i', $item['end_time']);
                    $item['duration'] = round(($item['end_time'] - $item['start_time']) / 3600, 1); // 小时
                    $item['is_urgent'] = $item['start_time'] - time() < 1800; // 30分钟内的为紧急
                    $item['status_text'] = $this->getScheduleStatusText($item['start_time'], $item['end_time']);
                    return $item;
                })
                ->toArray();
                
            $result['today'] = $todaySchedule;

            // 2. 近期日程（未来一周）
            $upcomingSchedule = Db::name('schedule')
                ->where([
                    ['admin_id', '=', $userId],
                    ['delete_time', '=', 0],
                    ['start_time', '>=', $tomorrow],
                    ['start_time', '<', $weekEnd]
                ])
                ->order('start_time asc')
                ->limit(15)
                ->select()
                ->each(function($item) {
                    $item['start_time_format'] = date('m-d H:i', $item['start_time']);
                    $item['end_time_format'] = date('H:i', $item['end_time']);
                    $item['day_of_week'] = date('w', $item['start_time']);
                    $item['is_weekend'] = in_array($item['day_of_week'], [0, 6]);
                    $item['relative_time'] = $this->getRelativeTime($item['start_time']);
                    return $item;
                })
                ->toArray();
                
            $result['upcoming'] = $upcomingSchedule;

            // 3. 本周日程概览（按天分组）
            $weeklySchedule = Db::name('schedule')
                ->where([
                    ['admin_id', '=', $userId],
                    ['delete_time', '=', 0],
                    ['start_time', '>=', $today],
                    ['start_time', '<', $weekEnd]
                ])
                ->field('*, date(from_unixtime(start_time)) as schedule_date')
                ->order('start_time asc')
                ->select()
                ->toArray();
                
            // 按日期分组
            $weeklyGrouped = [];
            foreach ($weeklySchedule as $schedule) {
                $date = $schedule['schedule_date'];
                if (!isset($weeklyGrouped[$date])) {
                    $weeklyGrouped[$date] = [
                        'date' => $date,
                        'date_format' => date('m-d', strtotime($date)),
                        'day_name' => $this->getDayName((int)date('w', strtotime($date))),
                        'schedules' => [],
                        'count' => 0
                    ];
                }
                $weeklyGrouped[$date]['schedules'][] = $schedule;
                $weeklyGrouped[$date]['count']++;
            }
            $result['weekly'] = array_values($weeklyGrouped);

            // 4. 日程统计数据
            $statistics = [
                'today_count' => count($todaySchedule),
                'upcoming_count' => count($upcomingSchedule),
                'week_total' => count($weeklySchedule),
                'urgent_count' => 0,
                'month_total' => 0
            ];
            
            // 紧急日程统计
            foreach ($todaySchedule as $schedule) {
                if ($schedule['is_urgent']) {
                    $statistics['urgent_count']++;
                }
            }
            
            // 本月总日程
            $statistics['month_total'] = Db::name('schedule')
                ->where([
                    ['admin_id', '=', $userId],
                    ['delete_time', '=', 0],
                    ['start_time', '>=', $today],
                    ['start_time', '<', $monthEnd]
                ])
                ->count();
                
            $result['statistics'] = $statistics;
            
        } catch (\Exception $e) {
            // 日程表不存在时返回默认值
            $result['statistics'] = [
                'today_count' => 0,
                'upcoming_count' => 0,
                'week_total' => 0,
                'urgent_count' => 0,
                'month_total' => 0
            ];
        }

        return $result;
    }

    /**
     * 获取消息统计
     * @param int $userId 用户ID
     * @return array
     */
    private function getMessageStats(int $userId): array
    {
        // 最新消息
        $latestMessages = Db::name('message')
            ->where([
                ['to_uid', '=', $userId],
                ['delete_time', '=', 0]
            ])
            ->order('create_time desc')
            ->limit(5)
            ->select()
            ->each(function($item) {
                $item['create_time_format'] = date('m-d H:i', $item['create_time']);
                $item['is_unread'] = $item['read_time'] == 0;
                return $item;
            })
            ->toArray();

        // 消息统计
        $messageStats = Db::name('message')
            ->where([
                ['to_uid', '=', $userId],
                ['delete_time', '=', 0]
            ])
            ->field('
                count(*) as total,
                sum(case when read_time = 0 then 1 else 0 end) as unread,
                sum(case when read_time > 0 then 1 else 0 end) as read
            ')
            ->find();

        return [
            'latest' => $latestMessages,
            'stats' => $messageStats,
            'unread_count' => $messageStats['unread'] ?? 0
        ];
    }

    /**
     * 获取汇总统计
     * @param array $stats 统计数据
     * @return array
     */
    private function getSummaryStats(array $stats): array
    {
        $summary = [
            'total_items' => 0,
            'pending_count' => 0,
            'unread_count' => 0
        ];

        // 统计概览数据
        if (!empty($stats['overview'])) {
            foreach ($stats['overview'] as $item) {
                $summary['total_items'] += $item['value'];
            }
        }

        // 统计待办数量
        if (!empty($stats['pending'])) {
            foreach ($stats['pending'] as $item) {
                $summary['pending_count'] += $item['count'];
            }
        }

        // 未读消息数量
        if (!empty($stats['messages']['stats']['unread'])) {
            $summary['unread_count'] = $stats['messages']['stats']['unread'];
        }

        return $summary;
    }

    /**
     * 获取用户基础信息
     * @param int $userId 用户ID
     * @return array
     */
    private function getUserInfo(int $userId): array
    {
        $user = Db::name('admin')
            ->alias('a')
            ->join('department d', 'a.did = d.id', 'LEFT')
            ->join('position p', 'a.position_id = p.id', 'LEFT')
            ->field('a.id, a.name, a.username, a.did, a.position_id, d.title as dept_name, p.title as position_name')
            ->where('a.id', $userId)
            ->find();

        if (!$user) {
            throw new \Exception('用户不存在');
        }

        return $user;
    }

    /**
     * 获取趋势数据
     * @param string $module 模块名称
     * @param int $userId 用户ID
     * @return array
     */
    private function getTrend(string $module, int $userId): array
    {
        $tableName = $this->getModuleTableName($module);
        $lastMonth = strtotime('-1 month');
        
        // 上月数量
        $lastMonthQuery = Db::name($tableName)
            ->where([
                ['delete_time', '=', 0],
                ['create_time', '<', $lastMonth]
            ]);
        $lastMonthQuery = $this->permissionService->applyPermissionToQuery($lastMonthQuery, $userId, $module);
        $lastMonthCount = $lastMonthQuery->count();

        // 本月数量
        $thisMonthQuery = Db::name($tableName)
            ->where([
                ['delete_time', '=', 0],
                ['create_time', '>=', $lastMonth]
            ]);
        $thisMonthQuery = $this->permissionService->applyPermissionToQuery($thisMonthQuery, $userId, $module);
        $thisMonthCount = $thisMonthQuery->count();

        $trend = 0;
        if ($lastMonthCount > 0) {
            $trend = round(($thisMonthCount - $lastMonthCount) / $lastMonthCount * 100, 1);
        } elseif ($thisMonthCount > 0) {
            $trend = 100;
        }

        return [
            'value' => $trend,
            'type' => $trend > 0 ? 'up' : ($trend < 0 ? 'down' : 'stable')
        ];
    }

    /**
     * 获取模块对应的表名
     * @param string $module 模块名称
     * @return string
     */
    private function getModuleTableName(string $module): string
    {
        $mapping = [
            'customer' => 'customer',
            'contract' => 'contract',
            'project' => 'project',
            'lawcase' => 'lawcase',
            'expense' => 'expense',
            'invoice' => 'invoice',
            'ticket' => 'ticket'
        ];

        return $mapping[$module] ?? $module;
    }

    /**
     * 获取审批类型名称
     * @param string $type 审批类型
     * @return string
     */
    private function getApprovalTypeName(string $type): string
    {
        $mapping = [
            'expense' => '报销',
            'invoice' => '开票',
            'ticket' => '收票',
            'contract' => '合同',
            'official' => '公文',
            'seal' => '用章',
            'purchase' => '采购',
            'project_task' => '任务',
            'customer' => '客户',
            'lawcase' => '法务',
            // 新增扩展类型
            'leave' => '请假',
            'overtime' => '加班',
            'business_trip' => '出差',
            'purchase_apply' => '采购申请',
            'asset_apply' => '资产申请',
            'meeting_room' => '会议室',
            'car_apply' => '用车申请',
            'training_apply' => '培训申请',
            'resignation' => '离职',
            'transfer' => '调转'
        ];

        return $mapping[$type] ?? $type;
    }
    
    /**
     * 获取日程状态文本
     * @param int $startTime 开始时间
     * @param int $endTime 结束时间
     * @return string
     */
    private function getScheduleStatusText(int $startTime, int $endTime): string
    {
        $now = time();
        
        if ($now < $startTime) {
            $diff = $startTime - $now;
            if ($diff < 1800) { // 30分钟内
                return '即将开始';
            } else {
                return '尚未开始';
            }
        } elseif ($now >= $startTime && $now <= $endTime) {
            return '进行中';
        } else {
            return '已结束';
        }
    }
    
    /**
     * 获取相对时间描述
     * @param int $timestamp 时间戳
     * @return string
     */
    private function getRelativeTime(int $timestamp): string
    {
        $diff = $timestamp - time();
        $days = floor($diff / 86400);
        $hours = floor(($diff % 86400) / 3600);
        
        if ($days > 0) {
            return $days . '天后';
        } elseif ($hours > 0) {
            return $hours . '小时后';
        } else {
            $minutes = floor($diff / 60);
            return $minutes > 0 ? $minutes . '分钟后' : '即将开始';
        }
    }
    
    /**
     * 获取星期名称
     * @param int $dayOfWeek 星期数字（0-6）
     * @return string
     */
    private function getDayName(int $dayOfWeek): string
    {
        $days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return $days[$dayOfWeek] ?? '未知';
    }
    
    /**
     * 获取综合业务统计（新增）
     * @param int $userId 用户ID
     * @return array
     */
    private function getComprehensiveStats(int $userId): array
    {
        $stats = [];
        $leaderDepartments = $this->getLeaderDepartments($userId);
        
        // 1. 本周工作量统计
        $weekStart = strtotime('this week Monday');
        $weekEnd = $weekStart + 7 * 86400;
        
        try {
            // 本周完成任务数
            $weekTasks = Db::name('project_task')
                ->where([
                    ['delete_time', '=', 0],
                    ['status', '=', 3], // 已完成
                    ['update_time', '>=', $weekStart],
                    ['update_time', '<', $weekEnd]
                ])
                ->where(function ($query) use ($userId) {
                    $query->whereOr([
                        ['admin_id', '=', $userId],
                        ['director_uid', '=', $userId]
                    ]);
                })
                ->count();
                
            $stats['week_completed_tasks'] = [
                'name' => '本周完成任务',
                'value' => $weekTasks,
                'type' => 'weekly_summary'
            ];
        } catch (\Exception $e) {
            $stats['week_completed_tasks'] = ['name' => '本周完成任务', 'value' => 0, 'type' => 'weekly_summary'];
        }
        
        // 2. 本月工作效率
        $monthStart = strtotime(date('Y-m-01'));
        try {
            $monthCompletedTasks = Db::name('project_task')
                ->where([
                    ['delete_time', '=', 0],
                    ['status', '=', 3], // 已完成
                    ['update_time', '>=', $monthStart]
                ])
                ->where(function ($query) use ($userId) {
                    $query->whereOr([
                        ['admin_id', '=', $userId],
                        ['director_uid', '=', $userId]
                    ]);
                })
                ->count();
                
            $monthTotalTasks = Db::name('project_task')
                ->where([
                    ['delete_time', '=', 0],
                    ['create_time', '>=', $monthStart]
                ])
                ->where(function ($query) use ($userId) {
                    $query->whereOr([
                        ['admin_id', '=', $userId],
                        ['director_uid', '=', $userId]
                    ]);
                })
                ->count();
                
            $efficiency = $monthTotalTasks > 0 ? round($monthCompletedTasks / $monthTotalTasks * 100, 1) : 0;
            
            $stats['month_efficiency'] = [
                'name' => '本月工作效率',
                'value' => $efficiency,
                'unit' => '%',
                'type' => 'efficiency'
            ];
        } catch (\Exception $e) {
            $stats['month_efficiency'] = ['name' => '本月工作效率', 'value' => 0, 'unit' => '%', 'type' => 'efficiency'];
        }
        
        // 3. 部门绯效排名（针对领导）
        if (!empty($leaderDepartments)) {
            try {
                $deptPerformance = [];
                foreach ($leaderDepartments as $deptId) {
                    $deptTasks = Db::name('project_task')
                        ->alias('t')
                        ->join('admin a', 't.admin_id = a.id')
                        ->where([
                            ['t.delete_time', '=', 0],
                            ['t.status', '=', 3],
                            ['t.update_time', '>=', $monthStart],
                            ['a.did', '=', $deptId]
                        ])
                        ->count();
                        
                    if ($deptTasks > 0) {
                        $deptName = Db::name('department')->where('id', $deptId)->value('title');
                        $deptPerformance[] = [
                            'dept_name' => $deptName,
                            'completed_tasks' => $deptTasks
                        ];
                    }
                }
                
                // 按完成任务数排序
                usort($deptPerformance, function($a, $b) {
                    return $b['completed_tasks'] - $a['completed_tasks'];
                });
                
                $stats['dept_performance'] = [
                    'name' => '部门绯效排名',
                    'data' => array_slice($deptPerformance, 0, 5), // 只显示前5名
                    'type' => 'ranking'
                ];
            } catch (\Exception $e) {
                $stats['dept_performance'] = ['name' => '部门绯效排名', 'data' => [], 'type' => 'ranking'];
            }
        }
        
        return $stats;
    }

    /**
     * 清除统计缓存
     * @param int $userId 用户ID
     */
    public function clearStatsCache(int $userId): void
    {
        $cacheKey = 'dashboard_stats_' . $userId;
        Cache::delete($cacheKey);
    }
    
    /**
     * 获取快捷操作数据（根据用户权限过滤）
     * @param int $userId 用户ID
     * @return array
     */
    private function getQuickActions(int $userId): array
    {
        // 定义所有可能的快捷入口及其对应的权限路径
        $allActions = [
            [
                'name' => '新建客户',
                'icon' => 'user-add',
                'url' => '/customer/add',
                'color' => '#1890ff',
                'permission_path' => '/customer/add' // 对应菜单路径
            ],
            [
                'name' => '新建合同', 
                'icon' => 'file-add',
                'url' => '/contract/add',
                'color' => '#52c41a',
                'permission_path' => '/contract/add'
            ],
            [
                'name' => '报销申请',
                'icon' => 'pay-circle',
                'url' => '/finance/expense/add', 
                'color' => '#fa8c16',
                'permission_path' => '/finance/expense'
            ],
            [
                'name' => '开票申请',
                'icon' => 'file-done',
                'url' => '/finance/invoice/add',
                'color' => '#722ed1',
                'permission_path' => '/finance/invoice'
            ],
            [
                'name' => '日程安排',
                'icon' => 'calendar',
                'url' => '/oa/plan/calendar',
                'color' => '#13c2c2',
                'permission_path' => '/oa/plan'
            ],
            [
                'name' => '工作日志',
                'icon' => 'edit',
                'url' => '/oa/work/add',
                'color' => '#eb2f96',
                'permission_path' => '/oa/work'
            ]
        ];
        
        // 获取用户的菜单权限
        $userPermissions = $this->getUserMenuPermissions($userId);
        
        // 根据权限过滤快捷入口
        $filteredActions = [];
        foreach ($allActions as $action) {
            // 检查用户是否有该权限
            $hasPermission = $this->hasMenuPermission($userPermissions, $action['permission_path']);
            
            if ($hasPermission) {
                // 移除 permission_path，不返回给前端
                unset($action['permission_path']);
                $filteredActions[] = $action;
            }
        }
        
        return $filteredActions;
    }
    
    /**
     * 获取用户的菜单权限列表
     * @param int $userId 用户ID
     * @return array
     */
    private function getUserMenuPermissions(int $userId): array
    {
        try {
            // 超级管理员拥有所有权限
            if ($userId == 1) {
                return ['*']; // 使用通配符表示所有权限
            }
            
            // 检查用户是否属于超级员工权限组(ID=1)
            $groupId = Db::name('admin')
                ->where('id', $userId)
                ->value('group_id');
            
            if ($groupId == 1) {
                return ['*'];
            }
            
            // 使用 AdminRule 模型获取用户权限
            $adminRuleModel = new \app\model\admin\AdminRule();
            $userRules = $adminRuleModel->getUserRules($userId);
            
            // 提取所有菜单路径
            $permissions = [];
            foreach ($userRules as $rule) {
                if (!empty($rule['mig_src'])) {
                    $permissions[] = $rule['mig_src'];
                }
            }
            
            return $permissions;
        } catch (\Exception $e) {
            // 发生异常时返回空权限
            return [];
        }
    }
    
    /**
     * 检查用户是否有指定菜单的权限
     * @param array $userPermissions 用户权限列表
     * @param string $menuPath 菜单路径
     * @return bool
     */
    private function hasMenuPermission(array $userPermissions, string $menuPath): bool
    {
        // 超级管理员有所有权限
        if (in_array('*', $userPermissions)) {
            return true;
        }
        
        // 直接匹配
        if (in_array($menuPath, $userPermissions)) {
            return true;
        }
        
        // 检查父级权限（例如：有 /customer 权限就有 /customer/add 权限）
        foreach ($userPermissions as $permission) {
            if (strpos($menuPath, $permission) === 0) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 获取用户权限摘要
     * @param int $userId 用户ID 
     * @return array
     */
    private function getUserPermissionSummary(int $userId): array
    {
        $leaderDepartments = $this->getLeaderDepartments($userId);
        
        return [
            'is_leader' => !empty($leaderDepartments),
            'department_count' => count($leaderDepartments),
            'can_approve' => !empty($leaderDepartments), // 简化判断
            'permission_level' => !empty($leaderDepartments) ? 'manager' : 'staff'
        ];
    }
    
    // getDefaultStats 方法已内联到 getDashboardStats 方法中，不再需要单独的方法
}